
## load packages and data

pacman::p_load(fixest, tidyverse, broom, data.table, countrycode)

df <- readRDS("Data/Regimedata/Measures_merged_covariates.rds")
names(df)
summary(df$GDP_PC_Farris)

df$v2cagenmob_nor <- (df$v2cagenmob - min(df$v2cagenmob, na.rm = T)) / (max(df$v2cagenmob, na.rm = T) - min(df$v2cagenmob, na.rm = T))
df$v2x_clphy*-1
df$v2x_clphy_nor <- (df$v2x_clphy - min(df$v2x_clphy, na.rm = T)) / (max(df$v2x_clphy, na.rm = T) - min(df$v2x_clphy, na.rm = T)) 




df2 <- df %>% 
  select(RegType_lied_EA, RegType_RoW_EA,  Politytype_Anocracy, status_fh_PF,
         HTW_RegType_MP_Autocracy, RegType_magaloni_EA, AnckarRegtype_MP_Autocracy, year, Final_Code) %>% 
  na.omit() %>%
  select(year, Final_Code) %>%
  left_join(df, by = c("year", "Final_Code"))


df2 <- df2 %>% 
  filter(RegType_lied_EA + RegType_RoW_EA + Politytype_Anocracy + status_fh_PF +
         HTW_RegType_MP_Autocracy + RegType_magaloni_EA + AnckarRegtype_MP_Autocracy >= 1)


names(df)  


## regime breakdown outcome
combinations <- tibble(Sample = c("RegType_lied_EA", "RegType_RoW_EA", "Politytype_Anocracy", "status_fh_PF", "AnckarRegtype_MP_Autocracy", "HTW_RegType_MP_Autocracy","RegType_magaloni_EA"),
                       name = c("LIED", "RoW", "Polity", "FH", "CPR", "ARD", "AoW"))




unique_countries <- unique(df2$Final_Code)

variance_list <- list()

for (i in 1:length(unique_countries)) {

  
excluded <- unique_countries[i]
  
  
results <- apply(combinations, 1, function(x) { 
  Regime <- x[1]
  name <- x[2]
  
  list(
    
 
    feols(reg_breakdown ~ negative_growth | Final_Code + year, cluster = "Final_Code", data = df2 %>% filter ( !!sym(Regime)  == 1 & Final_Code != excluded) ) %>%tidy()%>%
      mutate(Sample = "Overlapping Sample", Pred = "Recession", Measure = name),
    
    feols(reg_breakdown ~ log(GDP_PC_Farris)  | Final_Code + year, cluster = "Final_Code", data = df2 %>% filter ( !!sym(Regime)  == 1 & Final_Code != excluded) ) %>%tidy()%>%
      mutate(Sample = "Overlapping Sample", Pred = "log(GDP/PC)", Measure = name),
    
    feols(reg_breakdown ~ v2cagenmob| Final_Code + year, cluster = "Final_Code", data = df2 %>% filter ( !!sym(Regime)  == 1 & Final_Code != excluded) ) %>%tidy() %>%
      mutate(Sample = "Overlapping Sample", Pred = "Mobilization", Measure = name),
    
    
    feols(reg_breakdown ~ v2x_clphy_nor | Final_Code + year, cluster = "Final_Code", data = df2 %>% filter ( !!sym(Regime)  == 1 & Final_Code != excluded) )  %>%tidy() %>%
      mutate(Sample = "Overlapping Sample", Pred = "Repression", Measure = name)) %>% rbindlist()
  
})


coefplotframe <- results %>% 
  rbindlist %>% 
  as.data.frame



variance_list[[i]] <- coefplotframe %>% group_by(Pred) %>%
  summarize(variance_est = var(estimate),
            variance_stat = var(statistic)) %>%
  mutate(Country_excluded = excluded)

}


variance_df <- variance_list %>% 
  rbindlist %>% 
  as.data.frame 





variance_df <- variance_df%>%mutate(country_name = countrycode(Country_excluded, origin = "cown", destination = "country.name"))
variance_df$country_name <- if_else(variance_df$Country_excluded == 260,"Germany", variance_df$country_name)




top_countries <- variance_df %>% select(Pred, variance_stat, country_name) %>%
  group_by(Pred) %>%
  slice_min(variance_stat, n = 10) %>%
  arrange(Pred, variance_stat)



### Country list

collapsed_countries <- top_countries %>%
  group_by(Pred) %>%
  summarize(countries = paste(country_name, collapse = ", ")) %>%
  arrange(Pred)




##democratization outcome




combinations <- tibble(Sample = c("RegType_lied_EA", "RegType_RoW_EA", "Politytype_Anocracy", "status_fh_PF", "AnckarRegtype_MP_Autocracy", "HTW_RegType_MP_Autocracy","RegType_magaloni_EA"),
                       name = c("LIED", "RoW", "Polity", "FH", "CPR", "ARD", "AoW"),
                       Depvar =  c("F_RegType_lied_DEM", "F_RegType_RoW_DEM", "F_Politytype_Democracy", "F_status_fh_F", "F_AnckarRegtype_Democracy", "F_HTW_RegType_Democracy", "F_RegType_magaloni_DEM"))


names(df)


unique_countries <- unique(df2$Final_Code)

variance_list2 <- list()

for (i in 1:length(unique_countries)) {

excluded <- unique_countries[i]
  

results2 <- apply(combinations, 1, function(x) { 
  Regime <- x[1]
  name <- x[2]
  depvar <- x[3]
  
  list(
    
    feols(as.formula(paste(depvar, "~", "log(GDP_PC_Farris)", "| Final_Code + year")), cluster = "Final_Code", data = df2 %>% filter ( !!sym(Regime)  == 1& Final_Code != excluded) ) %>%tidy()%>%
      mutate(Sample = "Overlapping Sample", Pred = "log(GDP/PC)", Measure = name),
    
    feols(as.formula(paste(depvar, "~", "negative_growth", "| Final_Code + year")), cluster = "Final_Code", data = df %>% filter (!!sym(Regime) == 1& Final_Code != excluded) ) %>%tidy()%>%
      mutate(Sample = "Overlapping Sample", Pred = "Recession", Measure = name),
    
    
    feols(as.formula(paste(depvar, "~", "v2cagenmob", "| Final_Code + year")), cluster = "Final_Code", data = df2 %>% filter ( !!sym(Regime)  == 1& Final_Code != excluded) ) %>%tidy() %>%
      mutate(Sample = "Overlapping Sample", Pred = "Mobilization", Measure = name),
    
    feols(as.formula(paste(depvar, "~", "v2x_clphy", "| Final_Code + year")), cluster = "Final_Code", data = df2 %>% filter ( !!sym(Regime)  == 1& Final_Code != excluded) )  %>%tidy() %>%
      mutate(Sample = "Overlapping Sample", Pred = "Repression", Measure = name),
    
    feols(as.formula(paste(depvar, "~", "reg_breakdown", "| Final_Code + year")), cluster = "Final_Code", data = df2 %>% filter ( !!sym(Regime)  == 1& Final_Code != excluded) )  %>%tidy() %>%
      mutate(Sample = "Overlapping Sample", Pred = "Reg. Breakdown", Measure = name)) %>% rbindlist()
  
})

coefplotframe <- results2 %>% 
  rbindlist %>% 
  as.data.frame



variance_list2[[i]] <- coefplotframe %>% group_by(Pred) %>%
  summarize(variance_est = var(estimate),
            variance_stat = var(statistic)) %>%
  mutate(Country_excluded = excluded)

}


variance_df2 <- variance_list2 %>% 
  rbindlist %>% 
  as.data.frame 



variance_df2 <- variance_df2%>%mutate(country_name = countrycode(Country_excluded, origin = "cown", destination = "country.name"))

variance_df2 <- variance_df2 %>%
  mutate(Outcome = "Democratization")

variance_df <- variance_df %>%
  mutate(Outcome = "Regime Breakdown")


vardf <- rbind(variance_df2, variance_df)



top_countries <- vardf %>% select(Outcome, Pred, variance_stat, country_name) %>%
  group_by(Pred, Outcome) %>%
  slice_min(variance_stat, n = 10,with_ties = FALSE) %>%
  arrange(Outcome, Pred, variance_stat)

unique(vardf$Outcome)
unique(vardf$Pred)

variance_df2 %>% group_by(Pred) %>% summarize(var(variance_stat))

collapsed_countries <- top_countries %>%
  group_by(Outcome, Pred) %>%
  summarize(countries = paste(country_name, collapse = ", ")) %>%
  arrange(Outcome, Pred)



## Make dataaframe for Table G1
collapsed_countries

